package data_access

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

// InitDB initializes the database connection
func InitDB(host string, port int, username, password, dbname string) error {
	var err error
	// First connect without database to create it if needed
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return fmt.Errorf("连接数据库失败: %v", err)
	}

	// Create database if not exists
	result := DB.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", dbname))
	if result.Error != nil {
		return fmt.Errorf("创建数据库失败: %v", result.Error)
	}

	// Connect to the specific database
	dsn = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, dbname)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return fmt.Errorf("连接到数据库 %s 失败: %v", dbname, err)
	}

	// Auto migrate the schema
	err = DB.AutoMigrate(&User{}, &FollowRef{}, &Post{}, &PComment{}, &PLike{}, &PSave{})
	if err != nil {
		return fmt.Errorf("数据库迁移失败: %v", err)
	}

	return nil
}
